import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '@/views/HomeView.vue'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/home',
      name: 'home',
      component: HomeView,
      meta: { title: '首页'},
    },
    {
      path: '/articles',
      name: 'articles',
      component: () => import('@/views/article/ArticleListView.vue'),
      meta: { title: '文章列表' },
    },
    {
      path: '/article/:id',
      name: 'article-detail',
      component: () => import('@/views/article/ArticleDetailView.vue'),
      meta: { title: '文章详情' },
    },
    {
      path: '/write',
      name: 'article-edit',
      component: () => import('@/views/article/ArticleEditView.vue'),
      meta: { requiresAuth: true , title: '写文章'},
    },
    {
      path: '/profile',
      name: 'profile',
      component: () => import('@/views/user/UserProfileView.vue'),
      meta: { requiresAuth: true , title: '个人中心'},
    },
    {
      path: '/categories',
      name: 'categories',
      component: () => import('@/views/category/CategoryManageView.vue'),
      meta: { requiresAuth: true , title: '分类管理'},
    },
    {
      path: "/:catchAll(.*)",
      redirect: "/home",
      meta: { title: '首页'},
    }
  ],
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('token')
  if (to.meta.requiresAuth && !token) {
    document.title = '首页'
    next('/home')
  } else {
    //路径未被定义路由到首页
    if (to.path === '/' || to.path === '') {
      document.title = '首页'
      next('/home')
    }else{
      if(to.meta.title){
        document.title = to.meta.title as string
      }else{
        document.title = '博客'
      }
      next()
    }
  }
})

export default router
